﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using YioksPlanEditor.Models;

namespace YioksPlanEditor.Tools
{
    public class YioksTool
    {
        #region 软件是否已启动
        /// <summary>
        /// 软件是否已启动
        /// </summary>
        /// <returns></returns>
        public static bool IsSoftRuning(string softName)
        {
            var isRun = false;
            var count = 0;
            foreach (var p in Process.GetProcesses())
            {
                try
                {
                    if (p.MainModule != null)
                    {
                        System.Windows.Forms.MessageBox.Show(p.MainModule.FileName);
                        if (p.MainModule.FileVersionInfo.InternalName.ToLower().Equals(softName.ToLower()))
                        {
                            count++;
                        }
                    }
                }
                catch (Exception ex) { LogTool.Log(ex); }
            }

            if (count >= 2)
                isRun = true;
            return isRun;
        }

        /// <summary>
        /// 关闭软件
        /// </summary>
        /// <param name="softName">软件名称</param>
        public static void CloseSoftware(string softName)
        {
            var processIds = new List<int>();
            try
            {
                foreach (var p in Process.GetProcesses())
                {
                    try
                    {
                        if (p.MainModule != null)
                        {
                            var internalName = p.MainModule.FileVersionInfo.InternalName;
                            if (internalName == null) continue;
                            if (internalName.ToLower().Equals(softName.ToLower()))
                            {
                                processIds.Add(p.Id);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogTool.Log(ex);
                    }
                }
            }
            catch (Exception ex) { LogTool.Log(ex); }
            processIds.Sort();
            for (var i = processIds.Count - 1; i >= 0; i--)
            {
                try
                {
                    if (Process.GetCurrentProcess().Id != processIds[i])
                        Process.GetProcessById((processIds[i])).Kill();
                }
                catch (Exception ex) { LogTool.Log(ex); }
            }
        }

#endregion

        #region 设置开机启动项
        /// 是否启动
        /// 启动值的名称
        /// 启动程序的路径
        public static bool RunWhenStart(bool started, string name, string path)
        {
            var retrun = true;
            RegistryKey reg = null;
            try
            {
                reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (reg == null)
                    reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

                if (reg == null) retrun = false;
                else
                {
                    if (started)
                    {
                        reg.SetValue(name, path);
                    }
                    else
                        reg.SetValue(name, false);
                }
            }
            catch (Exception ex)
            {
                LogTool.Log(ex);
                retrun = false;
            }
            finally
            {
                if (reg != null)
                {
                    reg.Close();
                }
            }
            return retrun;
        }
        #endregion

        #region 执行批处理命令
        public static ProcessInfo Execute(string dosCommand, int outtime)
        {
            return Execute("C:\\Windows\\System32", dosCommand, outtime);
        }

        public static ProcessInfo Execute(string workdir, string dosCommand, int outtime)
        {
            var procesInfo = new ProcessInfo();
            if (!string.IsNullOrEmpty(dosCommand))
            {
                Process process = new Process();//创建进程对象  
                ProcessStartInfo startinfo = new ProcessStartInfo();//创建进程时使用的一组值，如下面的属性  
                startinfo.WorkingDirectory = workdir;
                startinfo.FileName = "cmd.exe";//设定需要执行的命令程序  
                //以下是隐藏cmd窗口的方法  
                startinfo.Arguments = "/c" + dosCommand;//设定参数，要输入到命令程序的字符，其中"/c"表示执行完命令后马上退出  
                startinfo.UseShellExecute = false;//不使用系统外壳程序启动  
                startinfo.RedirectStandardInput = false;//不重定向输入  
                startinfo.RedirectStandardOutput = true;//重定向输出，而不是默认的显示在dos控制台上  
                startinfo.CreateNoWindow = true;//不创建窗口  
                startinfo.RedirectStandardError = true;
                process.StartInfo = startinfo;
                try
                {
                    if (process.Start())//开始进程  
                    {
                        if (outtime == 0)
                        { process.WaitForExit(); }
                        else
                        { process.WaitForExit(outtime); }
                        procesInfo.OutputInfo = process.StandardOutput.ReadToEnd();//读取进程的输出  
                        procesInfo.ErrorInfo = process.StandardError.ReadToEnd();

                    }
                }
                catch (Exception ex)
                {
                    procesInfo.ErrorInfo = ex.ToString();
                }
                finally
                {
                    process.Close();
                }
            }
            return procesInfo;
        }
        #endregion
        #region 系统判断

        public static bool IsX86 => IntPtr.Size == 4;

        #endregion
    }
}
